package com.cloud.music.config.proxy;

import com.cloud.music.annotation.MusicServiceScan;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MusicServiceRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 获取SpringBootApplication自定义注解MusicServiceScan值
        AnnotationAttributes attrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(MusicServiceScan.class.getName()));

        if (attrs != null) {
            List<String> basePackages = new ArrayList<>();
            if (StringUtils.hasText(attrs.getString("value"))) {
                basePackages.add(attrs.getString("value"));
            }
            basePackages.addAll(Arrays.stream(attrs.getStringArray("basePackages")).filter(StringUtils::hasText).collect(Collectors.toList()));

            //将接口转换为BeanDefinition对象放入spring中
            //MusicServiceClassPathScannerr为自定义扫描类
            MusicServiceClassPathScanner classPathScanner = new MusicServiceClassPathScanner(beanDefinitionRegistry);
            classPathScanner.doScan(StringUtils.collectionToCommaDelimitedString(basePackages));
        }

    }
}
